﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using XMLToWordLib;
using System.IO;
using DevExpress.XtraTreeList;

namespace XmlAppliction.TJControl
{
    public partial class DevControlTreeList : DevExpress.XtraEditors.XtraUserControl
    {
        private DataSet TreeDs;//树列表
        private DateTime StartTime;
        private DateTime EndTime;
        private int ProBarValue = 0;
        private string tjID;

        private String SQL = "select   lpad(t.统计项编号,length(t.统计项编号)-2 ,'0') as  ParentID,t.统计项编号 as ID, t.统计项名称,t.执行语句,t.类型,' ' as  结果,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where 1=1 {0} order by t.统计项编号 asc ";
        public DevControlTreeList()
        {
            InitializeComponent();
        }

        public void DataBind(string conditionID,string startTimestr,string endTimestr)
        {
            tjID = conditionID;
            string condition = "";
            try
            {
                this.StartTime = DateTime.Parse(startTimestr);
                this.EndTime = DateTime.Parse(endTimestr);
                labelSTime.Text = startTimestr;
                labelETime.Text = endTimestr; 
            }
            catch {
                MessageBox.Show(" 构造参数错误！");
                return;
            }
            if (TreeDs != null) TreeDs.Dispose();
            try
            {
                if (conditionID != null && conditionID != "")
                {
                    condition = " and 统计项编号 like '" +conditionID+"%' ";
                }
                TreeDs = DBMgr.DbHelperOra.Query(string.Format(SQL, condition));

            }
            catch (Exception ex)
            {
                MessageBox.Show(" 数据库连接失败！" + ex.Message);
                return;
            }

            treeList1.DataSource = TreeDs.Tables[0].DefaultView;
            treeList1.ExpandAll();
            //设置标题
            foreach (DataRow dtrow in TreeDs.Tables[0].Rows)
            {
                if (tjID == dtrow["ID"].ToString().Trim())
                {
                    
                    //设置父窗体文本
                    try
                    {
                        Form form = this.ParentForm as Form;
                        form.Text = dtrow["统计项名称"].ToString();
                        GroupToolPanel.Text = "";
                    }
                    catch
                    {
                        GroupToolPanel.Text = dtrow["统计项名称"].ToString();
                    }
                }
            }


            setBtnEnable(false);
            TJTimer.Start(); 
            Thread thread = new Thread(new ThreadStart(BeginUpTree));
            thread.Start();
        }


        void setBtnEnable(bool flog)
        {
            if (!flog)
            {
                GroupToolPanel.Text += "( 统计中... )";
                progressBarControl1.Properties.Maximum = TreeDs.Tables[0].Rows.Count;
                progressBarControl1.Visible = true;

            }
            else
            {
                int indexNum = GroupToolPanel.Text.IndexOf('(');
                if (indexNum < 0) indexNum = GroupToolPanel.Text.Length;
                GroupToolPanel.Text = GroupToolPanel.Text.Substring(0, indexNum);
                
                //设置进度条  
                ProBarValue = 0; 
                progressBarControl1.Position = ProBarValue;
                GroupToolPanel.Text = "统计完成";
            }
            StatueTxt.EditValue = string.Format("{0}/{1}", ProBarValue, progressBarControl1.Properties.Maximum);
            GroupToolPanel.Enabled = flog;
            panelControl1.Visible = !flog; 
        }

        #region 多线程 统计数据

        bool IsTongJi = false;
        void BeginUpTree()
        {

            try
            {
                IsTongJi = true;
                DBLinkPool dbLinkPool = new DBLinkPool();
                DBLinkUser dbLinkUser = null;
                string linkUserID;
                string sql = "";

                foreach (DataRow dtrow in TreeDs.Tables[0].Rows)
                {
                     
                    dtrow["结果"] = "统计中...";
                    //-------查询出统计数据
                    if (dtrow["执行语句"].ToString().Length > 10)
                    {
                        try
                        {
                            linkUserID = dtrow["连接参数编号"].ToString();
                            dbLinkPool.Add(linkUserID, linkUserID, dtrow["连接参数"].ToString());
                            //dbLinkPool.Add(linkUserID, linkUserID, DBMgr.DbHelperOra.connectionString);//调试
                            dbLinkUser = dbLinkPool.GetLinkUser(linkUserID);
                            //连接数据库
                            dbLinkUser.Start();
                            sql = string.Format(dtrow["执行语句"].ToString(), StartTime.ToString(), EndTime.ToString());
                            dtrow["结果"] = dbLinkUser.GetTJNum(sql);
                        }
                        catch
                        {
                            dtrow["结果"] = -1;
                        }
                    }
                    else
                    {
                        dtrow["结果"] = "";
                    }

                    ProBarValue++;

                }

                //Thread.Sleep(5000);
                IsTongJi = false;

            }
            catch
            {
                MessageBox.Show("多线程统计结果出现错误！");
            }

        }

        #endregion

        private void TJTimer_Tick(object sender, EventArgs e)
        {
            if (!IsTongJi)//统计完成
            {
                setBtnEnable(true);
                TJTimer.Stop();
            }
            else
            {
                //设置进度条
                GroupToolPanel.Text = string.Format("处理进度：{0}/{1}", ProBarValue, progressBarControl1.Properties.Maximum);
                StatueTxt.EditValue = string.Format("{0}/{1}", ProBarValue, progressBarControl1.Properties.Maximum);
                progressBarControl1.Position = ProBarValue;
            }
        }

        private void BtnOutData_Click(object sender, EventArgs e)
        {


            string msgstr = ""; 
            int tempIndex = 0;
            saveFileDialog1.Filter = "xml文件(*.xml)|*.xml|Excel文件(*.xls)|*.xls";
            DialogResult showDialog = saveFileDialog1.ShowDialog(this);

            if (showDialog == DialogResult.OK)
            {
                if (File.Exists(saveFileDialog1.FileName))
                {
                    File.Delete(saveFileDialog1.FileName);
                }
                string fileType = saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf('.') + 1);
                if (fileType == "xml")
                {
                    tempIndex = saveFileDialog1.FileName.LastIndexOf('\\') - 1;
                    string path = saveFileDialog1.FileName;
                    string fold = path.Substring(0, tempIndex);
                    XMLHelper.writeXML(TreeDs, fold, StartTime.ToString(), EndTime.ToString(), DateTime.Now.ToString(), path); 
                    msgstr = "成功保存为XML文件！";
                }
                else if (fileType == "xls" || fileType == "xlsx")
                {
                    treeList1.ExportToXls(saveFileDialog1.FileName);
                    msgstr = "成功保存为Excel文档！";
                }
                else
                {
                    msgstr = "请输入正确的文件类型！";
                } 
                MessageBox.Show(msgstr);  
            }
             
            
        }

        //打开编号列
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (barButtonItem1.Caption == "关闭编号列")
            {
                barButtonItem1.Caption = "打开编号列";
                treCol统计项编号.Visible = false;
            }
            else
            {
                treCol统计项编号.Visible = true;
                barButtonItem1.Caption = "关闭编号列";
            }
        }

        //打开清单
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string nodeJG;
            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            if (node == null) return;
            nodeJG = node.GetValue("结果").ToString();
            if (nodeJG != "-1" && nodeJG != "")
            {
                if (Convert.ToInt32(nodeJG) > 30000)
                {
                    MessageBox.Show("一次查看数据量过大，无权查看！");
                    return;
                }
                openFrom(node.GetValue("ID").ToString());
            }
        }

        void openFrom(string tjid)
        {
            GridForm form = null; 
            try
            { 
                form = new GridForm(tjid, labelSTime.Text, labelETime.Text); 
                form.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (form != null) form.Dispose();
            }
        }
        //查看曲线分析图
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //lpad(t.统计项编号,length(t.统计项编号)-2 ,'0') as  ParentID,t.统计项编号 as ID, t.统计项名称,t.执行语句,t.类型,t.结果,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where 1=

            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            if (node == null) return;
            string tjid = node.GetValue("ID").ToString();
            string nodeJG = node.GetValue("结果").ToString();
            if (nodeJG != "-1" && nodeJG != "")
            { 
                DateTime stime = DateTime.Parse(labelSTime.Text);
                DateTime etime = DateTime.Parse(labelETime.Text);
                ChartsFrom chartsFrom = new ChartsFrom(stime, etime);
                //chartsFrom.MdiParent = this;
                chartsFrom.Show();  
                try
                {
                    chartsFrom.chartsShow.AddSerie(tjid);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "程序配置错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        //鼠标右键弹出右键菜单
        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
            if (e.Button == MouseButtons.Right)
            {
                treeList1.ContextMenuStrip = null;
                TreeListHitInfo hinfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
                DevExpress.XtraTreeList.Nodes.TreeListNode node = hinfo.Node;
                treeList1.FocusedNode = node;
                if (node != null)
                {
                     popupMenu1.ShowPopup(p);
                }

            }
        }

        private void btnReBind_Click(object sender, EventArgs e)
        {
            DataBind(tjID, StartTime.ToString(), EndTime.ToString());
        }
    }
}
